package com.by.mqsender.config;

import com.alibaba.nacos.spring.context.event.config.NacosConfigEvent;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.dromara.dynamictp.core.DtpRegistry;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Data
@Component
public class ByMqConfig implements SmartApplicationListener {

    private Map<String, String> tagTopicMap;

    @Resource
    private Environment environment;

    public String tag2Topic(String tag) {
        return this.tagTopicMap.get(tag);
    }

    public ThreadPoolExecutor executor() {
        return DtpRegistry.getDtpExecutor("mqSendReceipt");
    }

    @PostConstruct
    public void init() {
        refresh();
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return NacosConfigEvent.class.isAssignableFrom(eventType);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (!(event instanceof NacosConfigEvent)) {
            return;
        }
        refresh();
    }

    private void refresh() {
        ByMqConfig mqConfig = Binder.get(environment).bindOrCreate("", ByMqConfig.class);
        this.tagTopicMap = mqConfig.getTagTopicMap();
        log.info("[ByMqConfig][refresh] tagTopicMap:[{}]", this.tagTopicMap);
    }

}
